package com.devgroupvn.dota.youtube;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.devgroupvn.dota.Application;
import com.devgroupvn.dota.R;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class VideoStreamingPlayer extends Activity implements OnItemClickListener, OnPreparedListener,
		OnCompletionListener, OnClickListener
{
	public static String TYPE = "TYPE";
	public static String FIRST_LINK = "FIRST_LINK";
	public static String INDEX_FIRST_LINK = "INDEX_FIRST_LINK";
	public static int TYPE_PLAYLIST_DB = 0;
	public static int TYPE_PLAYLIST_SERVICE = 1;
	public static int TYPE_PLAYLIST_RANKING = 2;

	private MyVideoView _videoView;
	private ListView _listVideos;

	private List<YoutubeData> _youtubeDatas;
	private YoutubeAdapter _youtubeAdapter;
	private ProgressBar _loadingBar;
	private TextView _streaming;
	private FrameLayout _layoutVideo;
	private FrameLayout _layoutVideoForTouch;
	private boolean _isFullScreen;
	private String _youtubePlaylistId;
	private int _firstPosition;
	private int _currentPostion;
	private int _displayHeight;
	private LinearLayout _layoutPlayerController;

	MyMediaController _controller;
	GetLinkAsyncTask task;
	AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.video_streaming_player);
		adView = (AdView) findViewById(R.id.adView);
		_videoView = (MyVideoView) findViewById(R.id.videoViewYoutube);
		_videoView.setVisibility(VideoView.VISIBLE);
		_videoView.setOnPreparedListener(this);
		_videoView.setOnCompletionListener(this);
		_listVideos = (ListView) findViewById(R.id.listVideos);
		_loadingBar = (ProgressBar) findViewById(R.id.loadingIcon);
		_streaming = (TextView) findViewById(R.id.streaming);
		_layoutVideo = (FrameLayout) findViewById(R.id.layoutVideo);
		_layoutVideoForTouch = (FrameLayout) findViewById(R.id.layoutVideoForTouch);
		_layoutPlayerController = (LinearLayout) findViewById(R.id.playerController);

		Intent intent = getIntent();

		int type = intent.getExtras().getInt(TYPE);
		_isFullScreen = false;
		loadVideoList(type);
		setupAdwhirl();
		/*adView.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				adView.setVisibility(View.GONE);
			}
		});*/
	}
	
	private void setupAdwhirl()
	{
		try
		{
			final Handler handle = new Handler();
			final Runnable run = new Runnable()
			{

				@Override
				public void run()
				{
					AdRequest request = new AdRequest();
					adView.loadAd(request);
					handle.postDelayed(this, 5000);

				}
			};
			handle.postDelayed(run, 5000);
		}
		catch (Exception e)
		{

		}
	}

	@SuppressWarnings("unchecked")
	private void loadVideoList(int type)
	{
		if (type == TYPE_PLAYLIST_DB)
		{

		}
		else if (type == TYPE_PLAYLIST_SERVICE)
		{
			String firstLink = getIntent().getExtras().getString(FIRST_LINK);
			_currentPostion = getIntent().getExtras().getInt(INDEX_FIRST_LINK);
			_firstPosition = _currentPostion;

			Application app = (Application) getApplication();
			_youtubeDatas = (ArrayList<YoutubeData>) (app.getData("listYoutube"));
			_youtubeAdapter = new YoutubeAdapter(_listVideos, this, R.layout.youtube_tablecell,
					(ArrayList<YoutubeData>) _youtubeDatas, false);
			_listVideos.setAdapter(_youtubeAdapter);
			_listVideos.setOnItemClickListener(this);

			_controller = new MyMediaController(this, getWindow(), getWindowManager(), _layoutVideoForTouch,
					_layoutPlayerController);
			_controller.setFullscreenListeners(this);
			_videoView.setMediaController(_controller);
			task = new GetLinkAsyncTask();
			_loadingBar.setVisibility(ProgressBar.VISIBLE);
			task.execute(firstLink);
		}
		else if (type == TYPE_PLAYLIST_RANKING)
		{
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
	{
		_currentPostion = position;
		_firstPosition = _currentPostion;
		task.cancel(true);
		// if (_myMediaPlayer!=null && _myMediaPlayer.isPlaying())
		// {
		// _myMediaPlayer.stop();
		// }
		Log.i("VideoStreamingPlayer videolink", _youtubeDatas.get(_currentPostion).getVideoLink());
		playVideo(_youtubeDatas.get(_currentPostion).getVideoLink());
	}

	private void playVideo(String link)
	{
		task = new GetLinkAsyncTask();
		_loadingBar.setVisibility(ProgressBar.VISIBLE);
		_streaming.setVisibility(TextView.INVISIBLE);
		task.execute(link);
	}

	private class GetLinkAsyncTask extends AsyncTask<String, Void, List<Vid>>
	{

		@Override
		protected List<Vid> doInBackground(String... params)
		{
			List<Vid> result = null;
			try
			{
				result = VidLinkRetriever.retrieveMP4(params[0]);
			}
			catch (Exception e)
			{
				Log.d("Get Link Youtube", "Error get link MP4");
			}
			return result;
		}

		@Override
		protected void onPostExecute(List<Vid> result)
		{
			super.onPostExecute(result);
			if (result != null)
			{
				if (result.size() > 0)
				{
					int k = getResources().getDisplayMetrics().widthPixels;
					int m = getResources().getDisplayMetrics().heightPixels;
					// if (m == 1024 || k == 1024)
					// playVideoWithLink(result.get(result.size() - 1)
					// .getLink());
					// else
					playVideoWithLink(result.get(0).getLink());
				}
				else
				{
					Log.d("Get Link Youtube", "Couldn't get link MP4");
				}
			}
			else
			{
				Log.d("Get Link Youtube", "Result == NULL");
			}
		}
	}

	private void playVideoWithLink(String link)
	{
		Uri uri = Uri.parse(link);
		_videoView.setVideoURI(uri);
		// _videoView.requestFocus();
		_videoView.start();
	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
//		finish();
	}

	@Override
	public void onPrepared(MediaPlayer mp)
	{
		_youtubeAdapter.setNowPlaying(_currentPostion);
		_youtubeAdapter.notifyDataSetChanged();
		_streaming.setVisibility(TextView.VISIBLE);
		_loadingBar.setVisibility(ProgressBar.INVISIBLE);
	}

	@Override
	public void onCompletion(MediaPlayer mp)
	{
		selectNextVideo();
		if (_currentPostion != -1)
		{
			task.cancel(true);
			playVideo(_youtubeDatas.get(_currentPostion).getVideoLink());
		}
	}

	private void selectNextVideo()
	{
		if (_currentPostion + 1 < _youtubeDatas.size())
		{
			_currentPostion++;
		}
		else
		{
			_currentPostion = 0;
		}
		if (_currentPostion == _firstPosition)
		{
			_currentPostion = -1;
		}
	}

	private void switchToFullScreen()
	{
		_isFullScreen = true;
		_listVideos.setVisibility(View.GONE);
		this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		// int k = getResources().getDisplayMetrics().widthPixels;
		// int m = getResources().getDisplayMetrics().heightPixels;
		LinearLayout.LayoutParams paramsFullscreen = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
		_displayHeight = _layoutVideo.getHeight();
		_layoutVideo.setLayoutParams(paramsFullscreen);
		// _listVideos.setVisibility(ListView.GONE);
	}

	private void switchToNormal()
	{
		_isFullScreen = false;
		this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		int k = getResources().getDisplayMetrics().heightPixels;
		LinearLayout.LayoutParams paramsFullscreen = new LinearLayout.LayoutParams(k, _displayHeight);
		_layoutVideo.setLayoutParams(paramsFullscreen);

		_listVideos.setVisibility(ListView.VISIBLE);
	}

	public void onFullScreenClicked(View view)
	{
		if (_isFullScreen)
			switchToNormal();
		else switchToFullScreen();
	}

	@Override
	public void onClick(View v)
	{
		/*
		 * if (v.getId() == R.id.FullScreenToggleButton) { if (_isFullScreen)
		 * switchToNormal(); else { _listVideos.setVisibility(View.GONE);
		 * switchToFullScreen(); } }
		 */
	}
}
